package com.fdb.basic.framework.core.util;

import java.util.Objects;
import java.util.function.Consumer;
import java.util.function.Function;

/**
 * @description:在lambda表达式中将受检异常转为不受检异常的方便工具类
 * @date:2019年1月7日 下午4:06:01
 * @author:hengyh
 */
public class Try {
	public static <T, R> Function<T, R> ofFunction(UncheckedFunction<T, R> mapper) {
		Objects.requireNonNull(mapper);
		return t -> {
			try {
				return mapper.apply(t);
			} catch (Exception e) {
				throw new RuntimeException(e);
			}
		};
	}
	
	public static <T> Consumer<T> ofConsumer(UncheckedConsumer<T> consumer) {
		Objects.requireNonNull(consumer);
		return t -> {
			try {
				consumer.accept(t);
			} catch (Exception e) {
				throw new RuntimeException(e);
			}
		};
	}
	
	@FunctionalInterface
	public static interface UncheckedFunction<T, R> {
		R apply(T t) throws Exception;
	}
	
	@FunctionalInterface
	public static interface UncheckedConsumer<T> {
		void accept(T t) throws Exception;
	}
}
